import React, { Component } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Row, Select, Radio, Col } from 'antd';
import router from 'umi/router';
import HOCSelect from '@/components/AntDesign/Select';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import downloadFile, { getFileName } from '@/utils/utils';
import styles from '@/utils/utils.less';
import AddEmpInfor from '../../SocialService/SocialCard/AddEmpInfor';
import AddMatInfor from '../../SocialService/SocialCard/AddMatInfor';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    xl: { span: 8 },
    xxl: { span: 6 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
  },
};
const RadioGroup = Radio.Group;
@connect(({ archservicehandle: { updatedetail, coltFlag }, loading }) => ({
  updatedetail,
  coltFlag,
  loading: loading.effects['archservicehandle/fetchUpdateDetail'],
}))
class UpdateArchives extends Component {
  state = {};

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { rcrdSerHdlId } = location.query;
    this.setState({
      tabKey: location.query.submitFlag,
    });
    dispatch({
      type: 'archservicehandle/fetchUpdateDetail',
      payload: { rcrdSerHdlId },
    });
  }

  downLoad = item => {
    const file = item.split('|');
    downloadFile({ fileId: file[0], fileName: getFileName(file[1]) });
  };

  // 选择材料
  onSelectData = element => {
    const { elementArr, dispatch } = this.props;
    dispatch({
      type: 'card/matInfor',
      payload: { elementArr, element },
    });
    if (+element.inpType === 9 && Number(element.down) === 1) {
      if (element.downfile.response) {
        if (element.downfile.response.success) {
          this.downLoad(element.downfile.response.data);
        }
      } else {
        this.downLoad(element.downfile.uid.concat('|').concat(element.downfile.name));
      }
    }
  };

  // 提交运行
  saveUpdate = () => {
    const { updatedetail, form } = this.props;
    const { insCardHdl } = updatedetail;
    const insCardHdlData = insCardHdl;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const matlist = [];
      const rcrdSerHdl = {};
      const newValues = values;
      Object.keys(values).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(values[key].inpType) === '9') {
            let file = '';
            if (values[key].fileList && values[key].fileList.length) {
              values[key].fileList.map(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                } else if (!item.responss) {
                  file += item.uid
                    .concat('|')
                    .concat(item.name)
                    .concat(',');
                }
                return true;
              });
            }
            newValues[key].inpVal = file ? file.slice(0, file.length - 1) : undefined;
          }
          newValues[key].pkgPageDetailId = values[key].pageDetailId;
          matlist.push(newValues[key]);
        } else if (key === 'copyFiles') {
          rcrdSerHdl.copyFiles = values[key];
        } else if (key === 'masterFiles') {
          rcrdSerHdl.masterFiles = values[key];
        }
      });
      rcrdSerHdl.matFlag = +insCardHdlData.submitFlag === 2 ? values.matFlag : 1;
      rcrdSerHdl.rcrdSerHdlId = insCardHdlData.rcrdSerHdlId;
      rcrdSerHdl.sendId = insCardHdlData.sendId;
      rcrdSerHdl.source = insCardHdlData.source;
      rcrdSerHdl.serTypeId = insCardHdlData.serTypeId;
      rcrdSerHdl.vno = insCardHdlData.vno;
      rcrdSerHdl.submitFlag = '1';
      const param = {
        matlist,
        rcrdSerHdl,
      };
      const { dispatch } = this.props;
      dispatch({
        type: 'archservicehandle/updateList',
        payload: param,
        callback: response => {
          if (response) {
            router.goBack();
          }
        },
      });
    });
  };

  // 保存
  save = () => {
    const { updatedetail, form } = this.props;
    const { insCardHdl } = updatedetail;
    const insCardHdlData = insCardHdl;
    const { tabKey } = this.state;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const matlist = [];
      const rcrdSerHdl = {};
      const newValues = values;
      Object.keys(values).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(values[key].inpType) === '9') {
            let file = '';
            if (values[key].inpVal) {
              file += `${values[key].inpVal},`;
            }
            if (values[key].fileList && values[key].fileList.length) {
              values[key].fileList.map(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                } else if (!item.responss) {
                  file += item.uid
                    .concat('|')
                    .concat(item.name)
                    .concat(',');
                }
                return true;
              });
            }
            newValues[key].inpVal = file ? file.slice(0, file.length - 1) : undefined;
          }
          newValues[key].pkgPageDetailId = values[key].pageDetailId;
          matlist.push(newValues[key]);
        } else if (key === 'copyFiles') {
          rcrdSerHdl.copyFiles = values[key];
        } else if (key === 'masterFiles') {
          rcrdSerHdl.masterFiles = values[key];
        }
      });
      rcrdSerHdl.matFlag = +insCardHdlData.submitFlag === 2 ? values.matFlag : 1;
      rcrdSerHdl.rcrdSerHdlId = insCardHdlData.rcrdSerHdlId;
      rcrdSerHdl.sendId = insCardHdlData.sendId;
      rcrdSerHdl.source = insCardHdlData.source;
      rcrdSerHdl.serTypeId = insCardHdlData.serTypeId;
      rcrdSerHdl.vno = insCardHdlData.vno;
      rcrdSerHdl.submitFlag = +tabKey === 2 ? '2' : '1';
      const param = {
        matlist,
        rcrdSerHdl,
      };
      const { dispatch } = this.props;
      dispatch({
        type: 'archservicehandle/updateList',
        payload: param,
        callback: response => {
          if (response) {
            router.goBack();
          }
        },
      });
    });
  };

  // 关闭
  close = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/update')[0];
    router.push(`${tempUrl}/index`);
  };

  // 校验元素
  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      +value.inpType !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (+value.inpType === 1 || +value.inpType === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const { updatedetail, coltFlag, form } = this.props;
    const { getFieldDecorator } = form;
    const { empSendInfoVo, empBaseInfoVo, elementArr, matFileDictItem, insCardHdl } = updatedetail;
    const { tabKey } = this.state;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const renderElem = elementArrs =>
      elementArrs &&
      !!elementArrs.length &&
      elementArrs.map(element => (
        <Row key={element.pageDetailId}>
          <Col span={16}>
            <FormItem {...formItemLayouts} label={<span> {element.matName}</span>}>
              {getFieldDecorator(`mat_${element.pageDetailId}`, {
                rules: [
                  {
                    required: +element.reqFlag === 1,
                    validator: this.checkElement,

                    max: max(+element.inpType),
                  },
                ],
                initialValue: element,
              })(<AddMatInfor onChange={this.onSelectData} />)}
            </FormItem>
          </Col>
        </Row>
      ));

    return (
      <PageHeaderWrapper>
        <AddEmpInfor empSendInfoVo={empSendInfoVo} empBaseInfoVo={empBaseInfoVo} />
        <div className={styles.stepsAction}>
          {String(coltFlag) === '1' && (
            <Card>
              <Form>
                <Row>
                  <Col span={16}>
                    <FormItem {...formItemLayouts} label="原件材料:">
                      {getFieldDecorator('masterFiles', {
                        rules: [
                          {
                            required: false,
                            message: '请选择原件材料',
                          },
                        ],
                        initialValue:
                          insCardHdl && insCardHdl.masterFile ? insCardHdl.masterFile : undefined,
                      })(
                        <HOCSelect
                          style={{ width: '100%' }}
                          mode="multiple"
                          placeholder="请选择原件材料"
                          onChange={this.aaa}
                        >
                          {matFileDictItem &&
                            !!matFileDictItem.length &&
                            matFileDictItem.map(options => (
                              <Option key={options.itemCode}>{options.itemName}</Option>
                            ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={16}>
                    <FormItem {...formItemLayouts} label="复印件材料:">
                      {getFieldDecorator('copyFiles', {
                        rules: [
                          {
                            required: false,
                            message: '请选择复印件材料',
                          },
                        ],
                        initialValue:
                          insCardHdl && insCardHdl.copyFile ? insCardHdl.copyFile : undefined,
                      })(
                        <HOCSelect
                          style={{ width: '100%' }}
                          mode="multiple"
                          placeholder="请选择复印件材料"
                        >
                          {matFileDictItem &&
                            !!matFileDictItem.length &&
                            matFileDictItem.map(options => (
                              <Option key={options.itemCode}>{options.itemName}</Option>
                            ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  {renderElem(elementArr)}
                  {+insCardHdl.submitFlag === 2 ? (
                    <Col span={16} offset={1}>
                      <FormItem {...formItemLayouts} label="材料是否完整:">
                        {getFieldDecorator('matFlag', {
                          rules: [
                            {
                              required: true,
                              message: '请选择材料是否完整',
                            },
                          ],
                          initialValue:
                            insCardHdl && insCardHdl.matFlag ? `${insCardHdl.matFlag}` : undefined,
                        })(
                          <RadioGroup>
                            <Radio value="1">是</Radio>
                            <Radio value="2">否</Radio>
                          </RadioGroup>
                        )}
                      </FormItem>{' '}
                    </Col>
                  ) : null}
                </Row>
              </Form>
            </Card>
          )}
        </div>

        <FooterToolbar style={{ width: '100%' }}>
          <Button onClick={() => router.goBack()}>取消</Button>
          <Button type="primary" style={{ marginLeft: 8 }} onClick={() => this.save()}>
            保存
          </Button>
          {+tabKey === 2 ? (
            <Button type="primary" style={{ marginLeft: 8 }} onClick={() => this.saveUpdate()}>
              保存并提交运行
            </Button>
          ) : null}
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

const UpdateArchivesform = Form.create()(UpdateArchives);
export default UpdateArchivesform;
